from django.core.management.base import BaseCommand
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import RequestFactory
from io import BytesIO
from PIL import Image
from resume_management.models import BasicInfo
from resume_management.serializers import BasicInfoSerializer

class Command(BaseCommand):
    help = '调试头像上传问题'

    def create_test_image(self):
        """创建测试图片文件"""
        img = Image.new('RGB', (100, 100), color='red')
        img_io = BytesIO()
        img.save(img_io, format='JPEG')
        img_io.seek(0)
        
        uploaded_file = SimpleUploadedFile(
            name='test_avatar.jpg',
            content=img_io.getvalue(),
            content_type='image/jpeg'
        )
        
        return uploaded_file

    def test_serializer_validation(self):
        """测试序列化器验证"""
        self.stdout.write("=== 测试序列化器验证 ===")
        
        test_image = self.create_test_image()
        
        data = {
            'name': '张三',
            'gender': 'male',
            'phone': '13800138000',
            'email': 'zhangsan@example.com',
            'avatar': test_image
        }
        
        self.stdout.write("测试数据类型:")
        for key, value in data.items():
            self.stdout.write(f"  {key}: {type(value)} - {value}")
        
        serializer = BasicInfoSerializer(data=data)
        
        self.stdout.write(f"\n序列化器验证结果: {serializer.is_valid()}")
        
        if not serializer.is_valid():
            self.stdout.write(self.style.ERROR(f"验证错误: {serializer.errors}"))
        else:
            self.stdout.write(self.style.SUCCESS("验证通过!"))
            
        return serializer.is_valid()

    def test_model_field(self):
        """测试模型字段"""
        self.stdout.write("\n=== 测试模型字段 ===")
        
        avatar_field = BasicInfo._meta.get_field('avatar')
        self.stdout.write(f"Avatar字段类型: {type(avatar_field)}")
        self.stdout.write(f"Avatar字段配置: blank={avatar_field.blank}, null={avatar_field.null}")
        self.stdout.write(f"Upload to: {avatar_field.upload_to}")

    def handle(self, *args, **options):
        self.stdout.write("开始调试头像上传问题...\n")
        
        self.test_model_field()
        self.test_serializer_validation()
        
        self.stdout.write("\n调试完成!")
